package com.aspire.wap.core.common;

import java.io.UnsupportedEncodingException;
import java.util.StringTokenizer;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.ArrayUtils;

import com.aspirecn.core.commons.StringUtils;

/**
 * 这个类 <code>StringUtil</code> 集成了WAP组内常用的字符串操作方法，在WAP项目的开发中。
 * <p>
 * 
 * @author XXX1
 * @author XXX2
 * @author XXX3
 * @version 1.0
 * @since JDK1.5
 */
public class StringUtil
{

	/**
	 * 生成指定长度的随机字符串。
	 * 
	 * @param length
	 *            字符串长度，大于0的整型
	 * @return 生成的字符串
	 */
	public static String createRandomString(int length)
	{
		return StringUtils.createRandomString(length);
	}

	/**
	 * 过滤输入字符串，使之能够在WAP上浏览不出错。 依赖commons-lang-2.3.jar
	 * 
	 * @param str
	 *            源字符串
	 * @return 过滤后的字符串
	 */
	public static String filterStringToWML(String str)
	{
		String returnStr = str == null ? "" : str;
		//& --》 &amp;
		returnStr = StringUtils.replace(returnStr,
				"&amp;", "&");
		returnStr = StringUtils.replace(returnStr, "&",
				"&amp;");
//		returnStr = StringUtils.replace(returnStr,
//				"<<", "&lt;&lt;");
//		returnStr = StringUtils.replace(returnStr,
//				">>", "&gt;&gt;");
		returnStr = StringUtils.replace(returnStr, "<",
				"&lt;");
		returnStr = StringUtils.replace(returnStr, ">",
				"&gt;");
		returnStr = StringUtils.replace(returnStr,
				"\"", "&quot;");
		returnStr = StringUtils.replace(returnStr, "'",
				"&apos;");
		returnStr = StringUtils.replace(returnStr,
				"&amp;gt;", "&gt;");
		returnStr = StringUtils.replace(returnStr,
				"\n", "<br/>");

		return returnStr;
	}

	/**
	 * html实体转换的功能,部分终端会将中文转换成html实体传过来。 例如：你好 转换成html实体为 &#20320;&#22909;
	 * 
	 * @param str
	 *            源字符串
	 * @return 转换后的字符串
	 */
	public static String toUnicode(String s)
	{
		StringBuffer sb = new StringBuffer();
		//String sGB = null;
		if (s == null || s.equals(""))
		{
			return "";
		}
		for (int i = 0; i < s.length(); i++)
		{
			char cChar = s.charAt(i);
			// if(isChinese(cChar))
			if ((cChar) > 256)
			{
				if (isChinese2(cChar))
				{
					sb.append("&#x");
					sb.append(Integer.toHexString(cChar));
					sb.append(";");
				}
				continue;
			}
			else if ((cChar) > 127)
			{
				sb.append("&#x");
				sb.append(Integer.toHexString(cChar));
				sb.append(";");
				continue;
			}
			else if ((cChar) < 32)
			{ // 鍒犻櫎鍦?' ' (0x20)涓?涓嬬殑ascii
				continue;
			}
			switch (cChar)
			{
				case 32: // ' '
					sb.append("&nbsp;");
					break;

				case '$': // '$' 36
					sb.append("＄");
					break;

				case '\'': // '\'' 39
					sb.append("&apos;");
					break;

				case 34: // '"'
					sb.append("&quot;");
					break;

				case 38: // '&'
					sb.append("&amp;");
					break;

				case 60: // '<'
					sb.append("&lt;");
					break;

				case 62: // '>'
					sb.append("&gt;");
					break;
				case 0:
					break;
				case 20: // '\14'
					// sb.append("&gt;");
					break;
				default:
					sb.append(cChar);
					break;
			}
		}

		return sb.toString();
	}

	public static boolean isChinese(char c)
	{
		Character ch = new Character(c);
		String sCh = ch.toString();
		try
		{
			byte bb[] = sCh.getBytes("gb2312");
			if (bb.length > 1)
			{
				boolean flag = true;
				return flag;
			}
		}
		catch (UnsupportedEncodingException ue)
		{
			ue.printStackTrace();
			boolean flag1 = false;
			return flag1;
		}
		return false;
	}

	static sun.io.CharToByteGBK tool = new sun.io.CharToByteGBK();

	public static boolean isChinese2(char ch)
	{
		return tool.canConvert(ch);
	}

	/**
	 * 十六进制转字符串。
	 * 
	 * @param str
	 *            源字符串
	 * @return 转换后的字符串
	 */
	public static String hex2Str(String hex)
	{
		return hex2Str(hex, "UTF-8");

	}

	public static String hex2Str(String hex, String charset)
	{
		if (null == hex)
		{
			return "";
		}

		String res = "";
		byte[] bts = new byte[hex.length() / 2];
		for (int i = 0; i < bts.length; i++)
		{
			bts[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2),
					16);
		}

		try
		{
			if ("unicode".equalsIgnoreCase(charset))
			{
				res = new String(bts);
			}
			else
			{
				res = new String(bts, charset);
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		return res;
	}

	/**
	 * 字符串转十六进制。
	 * 
	 * @param str
	 *            源字符串
	 * @return 转换后的字符串
	 */
	public static String str2Hex(String source)
	{
		return str2Hex(source, "UTF-8");
	}

	public static String str2Hex(String source, String charset)
	{
		StringBuffer strBuff = new StringBuffer(100);
		String stmp = null;
		if (source == null)
		{
			return null;
		}

		try
		{
			byte[] strByte = source.getBytes(charset);
			for (int i = 0; i < strByte.length; i++)
			{
				stmp = Integer.toHexString(strByte[i] & 0xFF);
				if (stmp.length() == 1)
				{
					strBuff.append("0");
				}
				strBuff.append(stmp);
			}
		}
		catch (Throwable ex)
		{
			ex.printStackTrace();
		}
		return strBuff.toString().trim().toUpperCase();
	}

	public static String unicodeToGB(String str)
	{
		StringBuffer sb = new StringBuffer();
		StringTokenizer st = new StringTokenizer(str, "\\u");
		while (st.hasMoreTokens())
		{
			sb.append((char) Integer.parseInt(st.nextToken(), 16));
		}
		return sb.toString();
	}

	public static String gbk2utf8hex(String gbk)
	{
		StringBuilder utf8 = new StringBuilder();
		try
		{
			if (StringUtils.isNotBlank(gbk))
			{
				byte[] unicodebyte = gbk.getBytes("Unicode");
				if (unicodebyte != null && unicodebyte.length == 4)
				{
					utf8.append("\\u");
					utf8.append(Integer.toHexString(unicodebyte[2])
							.substring(6));
					utf8.append(Integer.toHexString(unicodebyte[3])
							.substring(6));
				}
				else
				{
					utf8.append(gbk);
				}
			}
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
		return utf8.toString();
	}

	public static String utf8Togb2312(String str)
	{
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < str.length(); i++)
		{
			char c = str.charAt(i);
			switch (c)
			{
				case '+':
					sb.append(' ');
					break;
				case '%':
					try
					{
						sb.append((char) Integer.parseInt(str.substring(i + 1,
								i + 3), 16));
					}
					catch (NumberFormatException e)
					{
						throw new IllegalArgumentException();
					}
					i += 2;
					break;
				default:
					sb.append(c);
					break;
			}
		}
		// Undo conversion to external encoding
		String result = sb.toString();
		String res = null;
		try
		{
			byte[] inputBytes = result.getBytes("8859_1");
			res = new String(inputBytes, "UTF-8");
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
		return res;
	}

	public byte[] gbk2utf8(String chenese)
	{
		char c[] = chenese.toCharArray();
		byte[] fullByte = new byte[3 * c.length];
		for (int i = 0; i < c.length; i++)
		{
			int m = c[i];
			String word = Integer.toBinaryString(m);
			StringBuffer sb = new StringBuffer();
			int len = 16 - word.length();
			for (int j = 0; j < len; j++)
			{
				sb.append("0");
			}
			sb.append(word);
			sb.insert(0, "1110");
			sb.insert(8, "10");
			sb.insert(16, "10");
			String s1 = sb.substring(0, 8);
			String s2 = sb.substring(8, 16);
			String s3 = sb.substring(16);
			byte b0 = Integer.valueOf(s1, 2).byteValue();
			byte b1 = Integer.valueOf(s2, 2).byteValue();
			byte b2 = Integer.valueOf(s3, 2).byteValue();
			byte[] bf = new byte[3];
			bf[0] = b0;
			fullByte[i * 3] = bf[0];
			bf[1] = b1;
			fullByte[i * 3 + 1] = bf[1];
			bf[2] = b2;
			fullByte[i * 3 + 2] = bf[2];
		}
		return fullByte;
	}

	/**
	 * MD5加密
	 * 
	 * @param message
	 * @return
	 */
	public static String getMD5(String str) {
		return DigestUtils.md5Hex(str);
		
	}
	
	/**
	 * 转换成十六进制字符串
	 * 
	 * @param src
	 * @return
	 */
	public static String bytesToHexString(byte[] src) {
		StringBuilder stringBuilder = new StringBuilder("");
		if ( ArrayUtils.isEmpty(src) ) {
			return null;
		}
		
		for (byte b : src)
		{
			int v = b & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		return stringBuilder.toString();
	}

	/**
	 * 十六进制字符串转换成字节数组
	 * @param hexString
	 * @return
	 */
	public static byte[] hexStringToBytes(String hexString) {
		if (StringUtils.isBlank(hexString)) {
			return null;
		}
		hexString = hexString.toUpperCase();
		int length = hexString.length() / 2;
		char[] hexChars = hexString.toCharArray();
		byte[] d = new byte[length];
		for (int i = 0; i < length; i++) {
			int pos = i * 2;
			d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
		}
		return d;
	}
	
	private static byte charToByte(char c) {
		return (byte) "0123456789ABCDEF".indexOf(c);
	}
}